//
//  SunResignVC.m
//  Xspcf
//
//  Created by sunshine on 16/10/17.
//  Copyright © 2016年 小小算盘. All rights reserved.
//

#import "SunResignVC.h"
#import "SunResignSuccessVC.h"
#import "SunWebVC.h"

@interface SunResignVC ()<UITextFieldDelegate>
{
    UITextField *_validate;
    UITextField *_code;
    UITextField *_recommand;
    UIButton *_timeBtn;
    UIButton *_nextBtn;
    UIButton *_securityBtn;
    NSTimer *_timer;
    UIButton *_delegate;
}
@end

@implementation SunResignVC

- (void)viewDidLoad {
    [super viewDidLoad];
    self.title = @"注册";
    self.view.backgroundColor = BACKGROUND;
    [self creatUI];
    // Do any additional setup after loading the view.
}

- (void)viewWillAppear:(BOOL)animated{
    [super viewWillAppear:animated];
    if (self.time > 0) {
        _timer = [NSTimer scheduledTimerWithTimeInterval:1 target:self selector:@selector(onTimer) userInfo:nil repeats:YES];
    }
}

- (void)dealloc{
    if (_timer) {
        [_timer invalidate];
        _timer = nil;
    }
}

- (BOOL)navigationShouldPopOnBackButton{
    [[Sun shareSun]alertAlign:NSTextAlignmentCenter title:@"" content:@"短信验证已下发，只差一步即可完成注册，确定取消注册！" left:@"取消" right:@"确定" cancel:^{
        [[Sun shareSun]hideShow];
    } sure:^{
        [[Sun shareSun]hideShow];
        [self.navigationController popViewControllerAnimated:YES];
    } To:self];
    return NO;
}

- (void)creatUI{
    UILabel *label = [[UILabel alloc]init];
    [self.view addSubview:label];
    [label lt_setTop:Y(18) to:nil save:YES];
    [label lt_setLeft:X(15) to:nil save:YES];
    label.font = [UIFont systemFontOfSize:13];
    [label setMarkup:[NSString stringWithFormat:@"<font color=\"#333333\">短信验证码已发送到：</font><font color=\"#ff5971\">%@</font>",self.phone]];
    UIView *bg1 = [[UIView alloc]init];
    [self.view addSubview:bg1];
    [bg1 lt_Top:SunEdgesMake(Y(8), 0, 0, Y(50)) to:label save:YES];
    bg1.backgroundColor = WHITE;
    UIImageView *img1 = [[UIImageView alloc]init];
    [bg1 addSubview:img1];
    [img1 lt_YcenterTo:nil save:YES];
    [img1 lt_setLeft:X(15) to:nil save:YES];
    img1.image = [UIImage imageNamed:@"login_code"];
    _code = [[UITextField alloc]init];
    [bg1 addSubview:_code];
    [_code lt_YcenterTo:nil save:YES];
    [_code lt_setLeft:X(60) to:nil save:YES];
    [_code lt_setWidth:X(230) save:YES];
    _code.textColor = BLACK;
    _code.font = [UIFont systemFontOfSize:16];
    _code.placeholder = @"请设置6~16位登录密码";
    _code.clearButtonMode = UITextFieldViewModeWhileEditing;
    _code.returnKeyType=UIReturnKeyDone;
    _code.delegate = self;
    _code.secureTextEntry = YES;
    _securityBtn = [[UIButton alloc]init];
    [bg1 addSubview:_securityBtn];
    [_securityBtn lt_YcenterTo:nil save:YES];
    [_securityBtn lt_setRight:X(15) to:nil save:YES];
    [_securityBtn setImage:[UIImage imageNamed:@"login_security"] forState:UIControlStateNormal];
    [_securityBtn setImage:[UIImage imageNamed:@"login_unsecurity"] forState:UIControlStateSelected];
    [_securityBtn addTarget:self action:@selector(changeSecurity) forControlEvents:UIControlEventTouchUpInside];
    UIView *bg2 = [[UIView alloc]init];
    [self.view addSubview:bg2];
    [bg2 lt_Top:SunEdgesMake(0, 0, 0, Y(50)) to:bg1 save:YES];
    bg2.backgroundColor = WHITE;
    UIImageView *img2 = [[UIImageView alloc]init];
    [bg2 addSubview:img2];
    [img2 lt_YcenterTo:nil save:YES];
    [img2 lt_setLeft:X(15) to:nil save:YES];
    img2.image = [UIImage imageNamed:@"login_validate"];
    _validate = [[UITextField alloc]init];
    [bg2 addSubview:_validate];
    [_validate lt_YcenterTo:nil save:YES];
    [_validate lt_setLeft:X(60) to:nil save:YES];
    [_validate lt_setWidth:X(230) save:YES];
    _validate.textColor = BLACK;
    _validate.font = [UIFont systemFontOfSize:16];
    _validate.placeholder = @"请输入验证码";
    _validate.keyboardType = UIKeyboardTypeNumberPad;
    _validate.clearButtonMode = UITextFieldViewModeWhileEditing;
    _validate.delegate = self;
    _validate.returnKeyType=UIReturnKeyDone;
    _timeBtn = [[UIButton alloc]init];
    [bg2 addSubview:_timeBtn];
    [_timeBtn lt_YcenterTo:nil save:YES];
    [_timeBtn lt_setRight:X(15) to:nil save:YES];
    _timeBtn.clipsToBounds = YES;
    _timeBtn.layer.cornerRadius = 3;
    [_timeBtn setBackgroundColor:RED forState:UIControlStateNormal];
    [_timeBtn setBackgroundColor:[HXColor colorWithHexString:@"FFB6C1"] forState:UIControlStateHighlighted];
    _timeBtn.titleLabel.font = [UIFont systemFontOfSize:12];
    _timeBtn.contentEdgeInsets = UIEdgeInsetsMake(4, 4, 4, 4);
    [_timeBtn setTitleColor:WHITE forState:UIControlStateNormal];
    [_timeBtn setTitle:@"获取验证" forState:UIControlStateNormal];
    [_timeBtn addTarget:self action:@selector(getValidateCode:) forControlEvents:UIControlEventTouchUpInside];
    UIView *bg3 = [[UIView alloc]init];
    [self.view addSubview:bg3];
    [bg3 lt_Top:SunEdgesMake(Y(28), 0, 0, Y(50)) to:bg2 save:YES];
    bg3.backgroundColor = WHITE;
    UIImageView *img3 = [[UIImageView alloc]init];
    [bg3 addSubview:img3];
    [img3 lt_YcenterTo:nil save:YES];
    [img3 lt_setLeft:X(15) to:nil save:YES];
    img3.image = [UIImage imageNamed:@"login_recommand"];
    _recommand = [[UITextField alloc]init];
    [bg3 addSubview:_recommand];
    [_recommand lt_YcenterTo:nil save:YES];
    [_recommand lt_setLeft:X(60) to:nil save:YES];
    [_recommand lt_setWidth:X(300) save:YES];
    _recommand.textColor = BLACK;
    _recommand.font = [UIFont systemFontOfSize:16];
    _recommand.placeholder = @"请输入邀请码/推荐人手机号(选填)";
    _recommand.keyboardType = UIKeyboardTypeNumberPad;
    _recommand.clearButtonMode = UITextFieldViewModeWhileEditing;
    _recommand.delegate = self;
    _recommand.returnKeyType=UIReturnKeyDone;
    UIView *line1 = [[UIView alloc]init];
    [self.view addSubview:line1];
    line1.backgroundColor = [HXColor colorWithHexString:@"dedede"];
    [line1 lt_Bottom:SunEdgesMake(0, 0, 0, 0.5) to:bg1 save:YES];
    UIView *line2 = [[UIView alloc]init];
    [self.view addSubview:line2];
    line2.backgroundColor = [HXColor colorWithHexString:@"dedede"];
    [line2 lt_Bottom:SunEdgesMake(X(56), 0, 0, 0.5) to:bg2 save:YES];
    UIView *line3 = [[UIView alloc]init];
    [self.view addSubview:line3];
    line3.backgroundColor = [HXColor colorWithHexString:@"dedede"];
    [line3 lt_Top:SunEdgesMake(0, 0, 0, 0.5) to:bg2 save:YES];
    UIView *line4 = [[UIView alloc]init];
    [self.view addSubview:line4];
    line4.backgroundColor = [HXColor colorWithHexString:@"dedede"];
    [line4 lt_Bottom:SunEdgesMake(0, 0, 0, 0.5) to:bg3 save:YES];
    UIView *line5 = [[UIView alloc]init];
    [self.view addSubview:line5];
    line5.backgroundColor = [HXColor colorWithHexString:@"dedede"];
    [line5 lt_Top:SunEdgesMake(0, 0, 0, 0.5) to:bg3 save:YES];
    _nextBtn = [[UIButton alloc]init];
    [self.view addSubview:_nextBtn];
    [_nextBtn lt_Top:SunEdgesMake(Y(42), X(15), X(15), Y(44)) to:bg3 save:YES];
    _nextBtn.clipsToBounds = YES;
    [_nextBtn setBackgroundColor:BLUE forState:UIControlStateNormal];
    [_nextBtn setBackgroundColor:[HXColor colorWithHexString:@"87CEFA"] forState:UIControlStateHighlighted];
    _nextBtn.layer.cornerRadius = 4;
    [_nextBtn setTitle:@"下一步" forState:UIControlStateNormal];
    [_nextBtn setTitleColor:WHITE forState:UIControlStateNormal];
    _nextBtn.titleLabel.font = [UIFont systemFontOfSize:17];
    [_nextBtn addTarget:self action:@selector(gotoResign) forControlEvents:UIControlEventTouchUpInside];
    _nextBtn.enabled = NO;
    _delegate = [[UIButton alloc]init];
    [self.view addSubview:_delegate];
    [_delegate lt_setTop:Y(10) to:_nextBtn save:YES];
    [_delegate lt_setSize:CGSizeMake(X(16), Y(16)) save:YES];
    [_delegate lt_setLeft:X(18) to:nil save:YES];
    [_delegate setImage:[UIImage imageNamed:@"tool_select"] forState:UIControlStateSelected];
    [_delegate setImage:[UIImage imageNamed:@"tool_unselect"] forState:UIControlStateNormal];
    _delegate.selected = YES;
    [_delegate addTarget:self action:@selector(acceptDelegate:) forControlEvents:UIControlEventTouchUpInside];
    UILabel *ll = [[UILabel alloc]init];
    [self.view addSubview:ll];
    [ll lt_YcenterTo:_delegate save:YES];
    [ll lt_setLeft:X(10) to:_delegate save:YES];
    ll.textColor = GRAY;
    ll.font = [UIFont systemFontOfSize:12];
    ll.text = @"我已阅读并同意";
    UIButton *webBtn = [[UIButton alloc]init];
    [self.view addSubview:webBtn];
    [webBtn lt_YcenterTo:ll save:YES];
    [webBtn lt_setLeft:0 to:ll save:YES];
    webBtn.titleLabel.font = [UIFont systemFontOfSize:12];
    [webBtn setTitle:@"《小算盘用户协议》" forState:UIControlStateNormal];
    [webBtn setTitleColor:BLUE forState:UIControlStateNormal];
    [webBtn doclick:^{
        SunWebVC *vc = [[SunWebVC alloc]init];
        vc.urlStr = [NSString stringWithFormat:@"%@/More/base_service?source=ios",KWAP];
        [self.navigationController pushViewController:vc animated:YES];
    }];
}

- (void)acceptDelegate:(UIButton *)btn{
    if (btn.isSelected) {
        btn.selected = NO;
    }else {
        btn.selected = YES;
    }
}

- (void)gotoResign{
    [[[UIApplication sharedApplication] keyWindow] endEditing:YES];
    
    if (_delegate.isSelected == NO) {
        [[Sun shareSun] showMsg:@"请阅读并同意小算盘用户协议"];
        return;
    }
    [[Sun shareSun]showActivity:self];
    NSUserDefaults *user = [NSUserDefaults standardUserDefaults];
    NSDictionary *param = @{@"password":_code.text,@"phone":self.phone,@"code":_validate.text,@"invitePhone":_recommand.text,@"idfa":[user objectForKey:@"ADID"]};
    
    NSString *url = [NSString stringWithFormat:@"%@%@",KURL,API_REGISTER];
    [HttpRequest postURL:url withParam:param success:^(id requestDic, NSString *msg) {
        [[Sun shareSun]hideActivity];
        [Sun setUser:[requestDic objectForKey:@"accessKey"] forKey:MD5];
        [Sun setUser:[requestDic objectForKey:@"desKey"] forKey:DES];
        [Sun setUser:[requestDic objectForKey:@"accessId"] forKey:ACCESSID];
        [Sun setUser:@"1" forKey:KLOGIN];
        [Sun setUser:self.phone forKey:PHONE];
        [[Sun shareSun]showMsg:@"注册成功"];
        SunResignSuccessVC *vc = [[SunResignSuccessVC alloc]init];
        [self.navigationController pushViewController:vc animated:YES];
    } failure:^(NSString *errorInfo, int code) {
        [[Sun shareSun]hideActivity];
        [[Sun shareSun]showMsg:errorInfo];
    }];
}

- (void)getValidateCode:(UIButton *)btn{
    if ([btn.titleLabel.text isEqualToString:@"重新获取"]) {
        [[Sun shareSun]alertAlign:NSTextAlignmentLeft title:@"收不到短信验证码，可能原因有:" content:@"1、输入的手机号不是本机\n2、手机处于停机欠费状态\n3、短信网关拥堵，建议稍后再尝试\n4、手机安全软件拦截，请暂时关闭拦截功能" left:@"重新获取短信验证码" right:nil cancel:^{
            [[Sun shareSun]hideShow];
            [btn setTitle:@"获取验证" forState:UIControlStateNormal];
            [self getValidateCode:btn];
        } sure:nil To:self];
        return;
    }
    [_timeBtn setTitle:@"发送中" forState:UIControlStateNormal];
    [[Sun shareSun]showActivity:self];
    NSString *url = [NSString stringWithFormat:@"%@%@",KURL,API_CODE];
    [HttpRequest postURL:url withParam:@{@"phone":self.phone,@"type":@"1"} success:^(id requestDic, NSString *msg) {
        [[Sun shareSun]hideActivity];
        [[Sun shareSun]showMsg:@"发送成功"];
        _time = 60;
        _timer = [NSTimer scheduledTimerWithTimeInterval:1 target:self selector:@selector(onTimer) userInfo:nil repeats:YES];
    } failure:^(NSString *errorInfo, int code) {
        [[Sun shareSun]hideActivity];
        [[Sun shareSun]showMsg:errorInfo];
        _timeBtn.enabled=YES;
        [_timeBtn setTitle:@"获取验证" forState:UIControlStateNormal];
    }];
}

- (void)onTimer{
    _timeBtn.enabled=NO;
    if(_time == 0){
        _timeBtn.enabled=YES;
        [_timeBtn setTitle:@"重新获取" forState:UIControlStateNormal];
        [_timer invalidate];
        _timer = nil;
        _time = 60;
        return;
    }
    _time --;
    [_timeBtn setTitle:[NSString stringWithFormat:@"剩余%ds",_time] forState:UIControlStateNormal];
}

- (void)changeSecurity{
    if (_securityBtn.isSelected) {
        _securityBtn.selected = NO;
        _code.secureTextEntry = YES;
    }else{
        _securityBtn.selected = YES;
        _code.secureTextEntry = NO;
    }
}

#pragma mark textField
- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string{
    NSString *result = textField.text;
    if (string.length > 0) {
        result = [result stringByAppendingString:string];
    }else if(result.length > 0){
        result = [result substringToIndex:result.length - 1];
    }
    _nextBtn.enabled = NO;
    if (textField == _code) {
        if ((_recommand.text.length == 0 || _recommand.text.length == 11) && result.length >= 6 && result.length <= 16 && _validate.text.length == 6) {
            _nextBtn.enabled = YES;
        }
    }
    if (textField == _validate) {
        if ((_recommand.text.length == 0 || _recommand.text.length == 11) && _code.text.length >= 6 && _code.text.length <= 16 && result.length >= 6) {
            _nextBtn.enabled = YES;
        }
        if (result.length > 6) {
            return NO;
        }
    }
    if (textField == _recommand) {
        if (_code.text.length >= 6 && _code.text.length <= 16 && _validate.text.length == 6 && (result.length == 0 || result.length >= 11)) {
            _nextBtn.enabled = YES;
        }
        if (result.length > 11) {
            return NO;
        }
    }
    return YES;
}

- (BOOL)textFieldShouldClear:(UITextField *)textField{
    _nextBtn.enabled = NO;
    if (textField == _recommand) {
        _nextBtn.enabled = YES;
    }
    return YES;
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
